package com.buaat.volunteer.web.config.security;

import javax.sql.DataSource;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import com.buaat.volunteer.service.IHelloService;

@EnableWebSecurity
@Controller
public class SecurityConfig extends WebSecurityConfigurerAdapter {

	@Autowired
	private IHelloService helloService;
	
	@Bean
	public DataSource dataSource() {
		org.springframework.jdbc.datasource.DriverManagerDataSource ds = new org.springframework.jdbc.datasource.DriverManagerDataSource();
		ds.setDriverClassName("com.mysql.jdbc.Driver");
		ds.setUrl("jdbc:mysql://localhost:3306/volunteer?characterEncoding=UTF8");
		ds.setUsername("root");
		ds.setPassword("2235143");
		return ds;
	}

	@RequestMapping("/login")
	public String login() {
		System.out.println(helloService.hello("小名"));
		return "login";
	}

	@Autowired
	public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
		auth.jdbcAuthentication().dataSource(dataSource())
				.usersByUsernameQuery("select loginid,password,1 from users where loginid = ?")
				.authoritiesByUsernameQuery("select loginid,'ROLE_USER' from users where loginid = ?");
	}

	@Override
	protected void configure(HttpSecurity http) throws Exception {
		http.authorizeRequests().anyRequest().authenticated().and().formLogin().loginPage("/login").permitAll();
	}

}
